//
//  NGRDataSourceModel.m
//  sdk2.0zhengquandasha
//
//  Created by Choi on 15/12/29.
//  Copyright © 2015年 palmaplus. All rights reserved.
//

#import "NGRDataSourceModel.h"
//#import "FMDB.h"
#import <sqlite3.h>
@interface NGRDataSourceModel ()<NGRDataSourceDelegate>

{
    //sqlite3 *newDB;
}
@property (nonatomic)sqlite3 *newDB;
@property (nonatomic,strong)NGRDataSource *dataSource;
//@property (nonatomic,strong)FMDatabase *db;
@property (nonatomic,strong)NSString *tempName;

@end
@implementation NGRDataSourceModel

static NGRDataSourceModel *dataSourceModel;

+(NGRDataSourceModel *)shareDataSourceModel{
    static dispatch_once_t onceDis;
    dispatch_once (&onceDis,^{
        dataSourceModel = [[NGRDataSourceModel alloc]init];
        dataSourceModel.dataSource = [[NGRDataSource alloc]init];
        dataSourceModel.dataSource.delegate = dataSourceModel;
        NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSLog(@"%@",documentDirectory);
        NSString *fileName = [documentDirectory stringByAppendingString:@"/poi.sqlite"];
        dataSourceModel.tempName = fileName;
        //dataSourceModel.db = [FMDatabase databaseWithPath:fileName];
        
    });
    return dataSourceModel;
}

-(BOOL)open{
    if (sqlite3_open([dataSourceModel.tempName UTF8String], &_newDB) !=SQLITE_OK) {
        sqlite3_close(_newDB);
        NSLog(@"数据库打开失败");
        return false;
    }else{
        NSLog(@"数据库打开成功");
        return true;
    }
}

-(void)searchAllPoiWithFloorId:(NGRID)floorId{
    [dataSourceModel.dataSource requestPoiChildren:floorId];
}

-(void)didPoiChildrenRespond:(NSArray *)pois{
        [self createTable:@"p_poi"];
    if (![self selectTable:@"冯建"]) {
        for (NGRLocationModel *model in pois) {
            NSLog(@" id = %lld parentID = %lld name = %@ type = %@ display = %@  address = %@",model.ID,model.parentID,model.name,model.type,model.display,model.address);
            if (model.name && ![model.name isEqualToString:@""]) {
                [self insertTabel:model];
            }
            
        }
    }
    //[self selectTable:@"冯"];
   
}
-(void)didPoiRespond:(NGRLocationModel *)poi{};
-(void)didPOISearchRespond:(NSArray *)pois{};

//创建表
-(void)createTable:(NSString *)tableName{
    NSString *str = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('id' integer PRIMARY KEY AUTOINCREMENT,'ngrid' integer,'parentid' integer,'name' text,'type' text, 'display' text,'address' text);",tableName];
/*
    if ([self.db open]) {
        NSLog(@"打开数据库成功");
        BOOL result = [self.db executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (id integer PRIMARY KEY AUTOINCREMENT,ngrid integer,parentid integer,name text,type text, display text,address text);",tableName]];
//                BOOL result = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS p_poi (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
        if (result) {
            NSLog(@"表%@创建成功",tableName);
        }else{
            NSLog(@"表%@创建失败",tableName);
        }
        
    }else {
        NSLog(@"打开数据库失败");
    }
    */
        [self execSql:str];

}

//sqlite数据库操作语句
-(void)execSql:(NSString *)sql{
    if ([dataSourceModel open]) {
        char *err;
        if (sqlite3_exec(self.newDB, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
            NSLog(@"数据库操作失败！");
        }else{
            NSLog(@"%@成功",sql);
        }
        sqlite3_close(self.newDB);
    }
}


//删除表
/*
-(void)deleteTable:(NSString *)tableName{
    if([self.db open]){
        NSString *str = [NSString stringWithFormat:@"DROP TABLE %@",tableName];
        if ([self.db executeUpdate:str]) {
        NSLog(@"删除%@表成功",tableName);
        }else{
        NSLog(@"删除%@表失败",tableName);
        }
    }else{
        NSLog(@"数据库打开失败");
    }
}
*/
//插入数据
-(void)insertTabel:(NGRLocationModel *)locationgModel{
    BOOL success = YES;
    /*
success = [self.db executeUpdate:@"INSERT INTO p_poi (id,parentid,name,type,display,address) values(?,?,?,?,?,?)",[NSNumber numberWithInt:locationgModel.ID],[NSNumber numberWithInt:locationgModel.parentID],locationgModel.name,locationgModel.type,locationgModel.display,locationgModel.address];
    if (success == NO) {
        NSLog(@"插入数据失败in%@",locationgModel.name);
    }
    */
    NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO p_poi (id,parentid,name,type,display,address) values(?,?,?,?,?,?)",[NSNumber numberWithInt:locationgModel.ID],[NSNumber numberWithInt:locationgModel.parentID],locationgModel.name,locationgModel.type,locationgModel.display,locationgModel.address];
    [self execSql:insertSql];
}


//查找数据
-(NSArray *)selectTable:(NSString *)name{
    NSString *str = [NSString stringWithFormat:@"SELECT * FROM p_poi WHERE name LIKE '%%%@%%'",name];
    /*
    [self.db open];
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    FMResultSet *rt = [self.db executeQuery:str];
    while ([rt next]) {
        if ([arr containsObject:[rt stringForColumn:@"name"]]) {
            continue;
        }
        [arr addObject:[rt stringForColumn:@"name"]];
    }
    NSArray *tempArr = arr;
    if (arr.count == 0) {
        return nil;
    }
    [self.db close];
    */
    
    sqlite3_stmt *statement;
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    if ([dataSourceModel open]) {
        if (sqlite3_prepare_v2(self.newDB, [str UTF8String], -1, &statement, nil)==SQLITE_OK) {
            while (sqlite3_step(statement)==SQLITE_ROW) {
                char *name = (char*)sqlite3_column_text(statement, 3);
                NSString *nsName = [[NSString alloc]initWithUTF8String:name];
                [arr addObject:nsName];
            }
        }
    }
    if (arr.count == 0) {
        return nil;
    }
    NSArray *tempArr = arr;
    return tempArr;
}

@end
